package com.teamide.client;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Client辅助类 从request、session中获取ClientSession
 * 
 * @author ZhuLiang
 *
 */
public class ClientHandler {

	public static final String APP_CLIENT_SESSION_KEY = "APP_CLIENT_SESSION";

	/**
	 * 新建Session
	 * 
	 * @return 客户端会话
	 */
	public static ClientSession newSession() {
		ClientSession session = new ClientSession();
		return session;
	}

	/**
	 * 新建Session 放在HttpSession中
	 * 
	 * @return 客户端会话
	 */
	public static ClientSession newSession(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		return newSession(request.getSession());

	}

	/**
	 * 新建Session 放在HttpSession中
	 * 
	 * @return 客户端会话
	 */
	public static ClientSession newSession(HttpSession httpSession) {
		if (httpSession == null) {
			return null;
		}
		ClientSession session = newSession();
		String key = getSessionKey(httpSession);
		httpSession.setAttribute(key, session);
		return session;
	}

	/**
	 * 从HttpSession中获取ClientSession，没有则会自动创建一个
	 * 
	 * @return 客户端会话
	 */
	public static ClientSession getSession(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		return getSession(request.getSession());

	}

	/**
	 * 从HttpSession中获取ClientSession，没有则会自动创建一个
	 * 
	 * @return 客户端会话
	 */
	public static ClientSession getSession(HttpSession httpSession) {
		if (httpSession == null) {
			return null;
		}
		String key = getSessionKey(httpSession);
		ClientSession session = null;
		if (httpSession.getAttribute(key) != null) {
			session = (ClientSession) httpSession.getAttribute(key);
		}

		if (session == null) {
			session = newSession(httpSession);
		}
		return session;
	}

	/**
	 * 获取在HttpSession中存放ClientSession的key
	 * 
	 * @return 客户端会话
	 */
	public static String getSessionKey(HttpServletRequest request) {

		String key = APP_CLIENT_SESSION_KEY;
		return key;
	}

	/**
	 * 获取在HttpSession中存放ClientSession的key
	 * 
	 * @return 客户端会话
	 */
	public static String getSessionKey(HttpSession httpSession) {

		String key = APP_CLIENT_SESSION_KEY;
		return key;
	}
}
